package com.web.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.web.mapper.UserMapper;
import com.web.model.User;
import com.web.model.dto.UserDto;

@Service
public class UserService {

	@Autowired
	UserMapper userMapper;
	
	public User getUser(int userId){
		return userMapper.selectByPrimaryKey(userId);
	}
	
	public User queryName(String userName){
		User userTo = new User();
		userTo.setUserName(userName);
		return userMapper.selectOne(userTo);
	}
	
	public void addUser(UserDto userDto){
		User user = new User();
		BeanUtils.copyProperties(userDto, user);
		userMapper.insert(user);
	}
	
	public void deleteUser(UserDto userDto){
		if (userDto.getUserName() == null) {
			throw new RuntimeException("用户姓名不可为空");
		}
		User user = this.queryOneUser(userDto);
		if (user == null) {
			throw new RuntimeException("没有查到用户");
		}
		userMapper.delete(user);
	}

	public void updateUser(UserDto userDto){
		if (userDto.getUserName() == null) {
			throw new RuntimeException("用户姓名不可为空");
		}
		User user = this.queryOneUser(userDto);
		BeanUtils.copyProperties(userDto, user, getNullPropertyNames(userDto));
		userMapper.updateByPrimaryKeySelective(user);
	}
	
	public List<User> queryUser(UserDto userDto){
		User userTO = new User();
		BeanUtils.copyProperties(userDto, userTO);
		return userMapper.select(userTO);
	}
	
	public User queryOneUser(UserDto userDto){
		User userTO = new User();
		BeanUtils.copyProperties(userDto, userTO);
		return userMapper.select(userTO).get(0);
	}
	
	/**
	 * 检查对象中null的属性
	 * 让spring BeanUtils copyproperties 支持忽略null的浅copy
	 */
	public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
